import { _HttpClient } from '@delon/theme';
import { Component, OnDestroy, OnInit } from '@angular/core';
import { NzMessageService, NzModalService, UploadFile } from 'ng-zorro-antd';
import { EmitterService } from '../../../service/emit.service';
import { ProductService } from '../../../service/prod/product.service';
import { CommService } from '../../../service/comm/comm.service';
import { Router } from '@angular/router';
import { PopService } from '../../../service/pop/pop.service';
import { ServiceResult } from '@core/constant';
import { catchError } from 'rxjs/operators';
import { of } from 'rxjs/index';
import { TranslateService } from '@ngx-translate/core';
import { isBlank } from '@delon/form/src/src/utils';

@Component({
  selector: 'pop-pops',
  templateUrl: './pops.component.html',
  styleUrls: ['./pops.component.less'],
})
export class PopPopsComponent implements OnInit, OnDestroy {
  q: any = {
    pageSize: 12,
    pageNumber: 0,
    brand: null,
    sap: null,
    sku: null,
  };
  visible = false;
  priceUnits = [{ text: '$', value: 'USD' }, { text: '€', value: 'EUR' }];
  brands = [];

  showAddList() {
    this.visible = true;
  }
  close(): void {
    this.visible = false;
    this.popItemVisible = false;
  }

  // badge
  dot = true;
  total = 0;
  addCount(item): void {
    if (item.count === undefined) {
      item.count = 0;
    }
    this.total++;
    item.count++;
  }

  minCount(item): void {
    if (item.count === undefined) {
      item.count = 0;
    }
    item.count--;
    if (item.count < 0) {
      item.count = 0;
    } else {
      this.total--;
      if (this.total <= 0) {
        this.total = 0;
      }
    }
  }

  // 套餐主对象
  pop: any = {
    id: null /*No show*/,
    sku: null,
    sap: null,
    description: null,
    img: null /*No show*/,
    unit: null /*No show*/,
    qty: null /*No show*/,
    netWeight: null,
    grossWeight: null,
    exw: null /*No show*/,
    cif: null /*No show*/,
    priceUnit: null,
    status: null,
    brand: null,
    ctnQty: null /*No show*/,
    cm: null,
    details: [],
  };

  // POP Item对象
  popItem: any = {
    id: null /*No show*/,
    sku: null,
    sap: null,
    description: null,
    count: null,
    img: null /*No show*/,
    material: null,
    brand: null,
    exw: null /*No show*/,
    cif: null /*No show*/,
    qty: null /*No show*/,
    netWeight: null,
    grossWeight: null,
    priceUnit: null,
    status: null,
    ctnQty: null /*No show*/,
    cm: null,
  };

  list: any[] = [];
  // list: any[] = [
  //   {
  //     img:
  //       'https://gw.alipayobjects.com/zos/rmsportal/HrxcVbrKnCJOZvtzSqjN.png',
  //     id: 'fake-list-0',
  //     status: 'active',
  //     description: '测试测试测试测试',
  //     sku: 'BOLON',
  //   },
  //   {
  //     img:
  //       'https://gw.alipayobjects.com/zos/rmsportal/gLaIAoVWTtLbBWZNYEMg.png',
  //     id: 'fake-list-1',
  //     status: 'active',
  //     description: '测试测试测试测试',
  //     sku: 'MOSION',
  //   },
  // ];

  changeBrand(status: boolean, idx: number) {
    if (idx === 0) {
      this.brandLines.map(i => (i.status = status));
    } else {
      if (this.brandLines[0].status === true) {
        this.brandLines[0].status = false;
      }
      this.brandLines[idx].status = status;
    }
    this.onScroll(false);
  }
  constructor(
    private http: _HttpClient,
    public msg: NzMessageService,
    private modalService: NzModalService,
    private emit: EmitterService,
    private productService: ProductService,
    private comm: CommService,
    private router: Router,
    private trans: TranslateService,
    private popService: PopService,
  ) {}

  ngOnInit() {
    this.onScroll(false);
    this.loadBrandLines();
    this.loadBrands();
    this.imgSuffix = this.comm.getGoodsUrl();
    this.uploadUrl = this.productService.uploadUrl();
    setTimeout(() => {
      this.emit.sendMessage('HIDE_REUSE_TAB');
    }, 100);
  }

  ngOnDestroy() {
    this.emit.sendMessage('SHOW_REUSE_TAB');
  }

  beforeUpload = (file: File) => {
    const isJPG = file.type === 'image/jpeg';
    const isPNG = file.type === 'image/png';
    if (!isJPG && !isPNG) {
      this.msg.create('warning', `不支持的格式: ${file.type}`);
    }
    const isLt2M = file.size / 1024 / 1024 < 2;
    if (!isLt2M) {
      this.msg.create('warning', '图片不能超过2MB!');
    }
    return (isJPG || isPNG) && isLt2M;
  };

  private getBase64(img: File, callback: (img: any) => void) {
    if (img) {
      const reader = new FileReader();
      reader.addEventListener('load', () => callback(reader.result));
      reader.readAsDataURL(img);
    }
  }

  handleChange(info: { file: UploadFile }): void {
    if (info.file.status === 'uploading') {
      this.loading = true;
      return;
    }
    if (info.file.status === 'done') {
      this.getBase64(info.file.originFileObj, (img: any) => {
        this.pop.img = info.file.response.rows[0].id;
        this.picUrl = this.comm.getGoodsUrl() + this.pop.img;
        this.loading = false;
      });
    }
    if (info.file.status === 'error') {
      this.msg.create('error', info.file.error.error);
    }
  }
  reset() {
    (this.pop.sku = null),
      (this.pop.sap = null),
      (this.pop.description = null),
      (this.pop.netWeight = null),
      (this.pop.grossWeight = null),
      (this.pop.priceUnit = null),
      (this.pop.status = null),
      (this.pop.brand = null),
      (this.pop.cm = null),
      (this.salestatus = true);
    this.pop.status = null;
  }
  back() {
    this.router.navigate(['/pop/list']);
  }

  uploadUrl = '';
  picUrl = '';
  imgSuffix = '';
  loading = true;
  salestatus = true;

  current = 0;
  step = 0;

  pre(): void {
    this.current -= 1;
    this.changeContent();
  }

  next(): void {
    let flag = false;
    const brands = new Set();
    for (const detail of this.list) {
      if (detail.count !== undefined && detail.count !== 0) {
        brands.add(detail.brand);
      } else {
        continue;
      }
    }
    if (brands.size > 1) {
      this.msg.create('info', '非同一品牌无法添加到同一个套餐下');
      return;
    } else {
      flag = true;
    }
    if (this.total === 0) {
      flag = false;
    }
    if (!flag) {
      this.msg.create('info', '请挑选POP单品');
      return;
    }
    this.current += 1;
    const temp = Array.from(brands);
    this.pop.brand = temp.pop();
    this.generateMsg();
    this.changeContent();
  }

  showImg = true;
  generateMsg() {
    let tmpSku = '';
    let tmpSap = '';
    const set = new Set();
    for (const detail of this.list) {
      if (detail.count !== undefined && detail.count !== 0) {
        set.add(detail);
        // 计算detail总价、总数等
        const temExw = detail.exw * detail.count;
        const temCIF = detail.cif * detail.count;
        const temQTY = detail.qty * detail.count;
        const temCntQty = detail.ctnQty * detail.count;
        const tmpGW = detail.grossWeight * detail.count;
        const tmpNW = detail.netWeight * detail.count;

        this.pop.details.push(detail);
        this.pop.exw += temExw;
        this.pop.cif += temCIF;
        this.pop.qty += temQTY;
        this.pop.ctnQty += temCntQty;
        this.pop.grossWeight += tmpGW;
        this.pop.netWeight += tmpNW;
        // 如果没有设置对应的字段，则自动拼接
        if (
          detail.sku != null ||
          detail.sku !== undefined ||
          detail.sku !== ''
        ) {
          tmpSku += detail.sku + '&';
        }
        if (
          detail.sap != null ||
          detail.sap !== undefined ||
          detail.sap !== ''
        ) {
          tmpSap += detail.sap + '&';
        }
        // if (
        //   detail.description != null ||
        //   detail.description !== undefined ||
        //   detail.description !== ''
        // ) {
        //   tmpDescription += detail.description + '&';
        // }
      }
    }
    if (set.size === 1) {
      set.forEach(e => {
        this.showImg = false;
        this.pop.img = e.img;
      });
    } else {
      this.pop.img = null;
      this.showImg = true;
    }
    this.pop.status = this.salestatus ? 'normal' : 'disabled';
    // this.pop.unit = this.pop.unit != null ? '付' : this.pop.unit;
    // 去除尾部多余的&

    if (this.isBlank(this.pop.sku)) {
      let sliceSku = '';
      if (tmpSku.endsWith('&')) {
        sliceSku = tmpSku.slice(0, -1);
        this.pop.sku = sliceSku;
      }
    }
    if (this.isBlank(this.pop.sap)) {
      let sliceSap = '';
      if (tmpSap.endsWith('&')) {
        sliceSap = tmpSap.slice(0, -1);
        this.pop.sap = sliceSap;
      }
    }
    // if (this.isBlank(this.pop.description)) {
    //   let sliceDesc = '';
    //   if (tmpDescription.endsWith('&')) {
    //     sliceDesc = tmpDescription.slice(0, -1);
    //     this.pop.description = sliceDesc;
    //   }
    // }
  }

  // 保存套餐
  save(): void {
    this.pop.priceUnit = 'USD';
    this.popService
      .save(this.pop)
      .pipe(
        catchError(err => {
          return of(err);
        }),
      )
      .subscribe(ret => {
        if (ret.status === 200 || ret.code === 200) {
          this.msg.create('success', '保存成功');
          this.router.navigate(['/pop/list/']);
        } else {
          if (ret.msg) {
            this.msg.create('error', ret.msg);
          } else {
            this.msg.create('error', ret.message);
          }
        }
      });
  }

  isBlank(str: string) {
    if (str == null || str === undefined || str === '') {
      return true;
    }
    return false;
  }

  changeContent(): void {
    switch (this.current) {
      case 0: {
        this.step = 0;
        break;
      }
      case 1: {
        this.step = 1;
        break;
      }
      case 2: {
        break;
      }
      default: {
      }
    }
  }
  brandLines = [];
  loadBrandLines() {
    const lang = this.trans.currentLang || this.trans.defaultLang;
    this.brandLines = [];
    this.brandLines.push({ id: '0', text: 'ALL', value: '', status: false });
    this.comm.getBrand().subscribe(data => {
      const ret: ServiceResult = <ServiceResult>data;
      if (ret.status === 200) {
        for (const row of ret['data']['rows']) {
          this.brandLines.push({
            id: lang === 'en' ? row.labelEnUs : row.labelDefault,
            text: lang === 'en' ? row.labelEnUs : row.labelDefault,
            value: row.value,
            status: false,
          });
        }
      }
    });
  }

  loadBrands() {
    const lang = this.trans.currentLang || this.trans.defaultLang;
    this.brands = [];
    this.comm.getBrand().subscribe(data => {
      const ret: ServiceResult = <ServiceResult>data;
      if (ret.status === 200) {
        for (const row of ret['data']['rows']) {
          this.brands.push({
            text: lang === 'en' ? row.labelEnUs : row.labelDefault,
            value: row.value,
          });
        }
      }
    });
  }

  popItemVisible = false;
  view(item) {
    console.log(item.id);
    this.popService
      .listPopItemById(item.id)
      .pipe(
        catchError(err => {
          return of(err);
        }),
      )
      .subscribe(ret => {
        if (ret.status === 200 || ret.code === 200) {
          this.popItem = ret.data;
          this.popItemVisible = true;
        } else {
          if (ret.msg) {
            this.msg.create('error', ret.msg);
          } else {
            this.msg.create('error', ret.message);
          }
        }
      });
  }
  previewImage = '';
  previewVisible = false;

  showImage(src) {
    this.previewImage = src;
    this.previewVisible = true;
  }

  hasMore = true;
  onScroll(append): void {
    this.loading = true;
    this.total = 0;
    if (append) {
      this.q.pageNumber = this.q.pageNumber + 1;
    } else {
      this.q.pageNumber = 1;
      this.hasMore = true;
    }
    if (this.hasMore) {
      const lang = this.trans.currentLang || this.trans.defaultLang;
      this.http
        .get(this.popService.listPopItems2(), this.preHandle())
        .pipe(
          catchError(err => {
            this.loading = false;
            this.msg.create(
              'error',
              lang === 'en'
                ? 'Fail Loading,Please try again'
                : '加载数据失败，请重新加载',
            );
            return of(err);
          }),
        )
        .subscribe((res: any) => {
          if (
            res.data.rows.length === 0 ||
            res.data.rows.length < this.q.pageSize
          ) {
            this.hasMore = false;
          } else {
            this.hasMore = true;
          }
          if (append) {
            this.list = this.list.concat(res.data.rows);
          } else {
            this.list = res.data.rows;
          }
          for (const row of this.list) {
            if (row.count === undefined) {
              row.count = 0;
            }
          }
          this.loading = false;
        });
    } else {
      this.loading = false;
    }
  }
  preHandle() {
    const tmpBrands = [];
    this.brandLines
      .filter(i => {
        return i.text !== '全部' && i.text !== 'ALL' && i.status;
      })
      .forEach(v => {
        tmpBrands.push(v.value);
      });
    return {
      // sku: this.q.sku !== '' ? this.q.sku : null,
      sap: this.q.sap !== '' ? this.q.sap : null,
      // brand: this.q.brand !== '' ? this.q.brand : null,
      batchBrandLine: tmpBrands.toString(),
      pageSize: this.q.pageSize,
      pageNumber: this.q.pageNumber,
      status: 'normal',
    };
  }

  removeItem(item) {
    this.total -= item.count;
    item.count = 0;
    return;
  }
}
